package com.qupeng.demo.kafka.kafkaspringbootproducer.avro;

import com.qupeng.demo.kafka.kafkaspringbootproducer.config.KafkaProperties;
import com.qupeng.demo.kafka.kafkaspringbootproducer.model.CommonResponse;
import com.qupeng.demo.kafka.kafkaspringbootproducer.model.ProduceSuccessResponse;
import com.qupeng.demo.kafka.kafkaspringbootproducer.producer.KafkaService;
import com.qupeng.demo.kafka.kafkaspringbootproducer.producer.RandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.support.SendResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/avro/messages")
public class KafkaAvroController {

    @Autowired
    private KafkaService<Integer, Product> kafkaService;

    @Autowired
    private KafkaProperties kafkaProperties;

    @PostMapping("")
    public CommonResponse<ProduceSuccessResponse<Integer, Product>> produce(@RequestBody Product product) {
        try {
            SendResult<Integer, Product> sendResult = kafkaService.sendToKafkaSync(kafkaProperties.getTopics().get(0), RandomNumberGenerator.getRandom(100), product);
            return new CommonResponse<>("avro-producer-controller", new ProduceSuccessResponse<Integer, Product>((sendResult)));
        } catch (ExecutionException | InterruptedException e) {
            return new CommonResponse<>("002-producer-controller", e.getMessage(), "avro-producer-controller");
        }
    }
}
